<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/notice' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>课程管理</el-breadcrumb-item>
      <el-breadcrumb-item>课程信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card shadow="never">
      <!-- 课程筛选 -->
      <el-row :gutter="20" type="flex" justify="space-between">
        <!-- 按学年查询 -->
        <el-col :span="4">
          <el-select
            v-model="queryInfo.year"
            placeholder="按学年查询"
            size="small"
            class="borderColor"
            @change="getLessonList"
          >
            <el-option v-for="item in getYear" :key="item.label" :value="item.label"></el-option>
          </el-select>
        </el-col>
        <!-- 按学期查询 -->
        <el-col :span="4" :pull="3">
          <el-select
            v-model="queryInfo.term"
            placeholder="按学期查询"
            size="small"
            class="borderColor"
            @change="getLessonList"
          >
            <el-option v-for="item in terms" :key="item.label" :value="item.label"></el-option>
          </el-select>
        </el-col>
        <!-- 按课程名称查询 -->
        <el-col :span="10">
          <el-input
            v-model="queryInfo.subject"
            placeholder="请输入课程名称"
            prefix-icon="el-icon-search"
            size="small"
            @change="getLessonList"
            clearable
          ></el-input>
        </el-col>
      </el-row>
      <!-- 课程列表 -->
      <el-table
        :data="lessonData"
        style="width: 100%"
        highlight-current-row
        stripe
        class="lessonTable"
      >
        <el-table-column prop="id" label="课程编码" width="130"></el-table-column>
        <el-table-column prop="subject" label="课程名称"></el-table-column>
        <el-table-column prop="period" label="课程时间">
          <template slot-scope="scope">{{scope.row.period + '周'}}</template>
        </el-table-column>
        <el-table-column label="课程性质">
          <template slot-scope="scope">
            <el-tag>{{scope.row.nature}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="课程学分"></el-table-column>
        <el-table-column prop="teacher.username" label="教师姓名"></el-table-column>
        <el-table-column prop="teacher.college" label="所属学院"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="getLessonInfo(scope.row._id)">修改</el-button>
            <el-button size="mini" type="danger" @click="isDeleteLesson(scope.row._id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页查询 -->
      <el-row type="flex" justify="space-between">
        <!-- 分页组件 -->
        <el-col :span="10">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="handlePageChange"
          ></el-pagination>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="2">
          <el-button size="small" type="primary" @click="showAddDrawer">添加课程</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加课程弹出框 -->
    <el-drawer
      title="添加课程"
      :visible.sync="addDrawer"
      direction="ltr"
      class="addDrawer"
      @close="()=>{this.$refs.lessonFormRef.resetFields()}"
    >
      <el-form
        ref="lessonFormRef"
        :rules="addFormRules"
        :model="lessonForm"
        label-width="70px"
        size="medium"
        class="addLessonForm"
      >
        <el-form-item label="学年：" prop="year">
          <el-select v-model="lessonForm.year" placeholder="请选择学年" style="width:100%">
            <el-option v-for="item in getYear" :key="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期：" prop="term">
          <el-radio-group v-model="lessonForm.term">
            <el-radio :label="1">第一学期</el-radio>
            <el-radio :label="2">第二学期</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课时：" prop="period">
          <el-input-number
            v-model="lessonForm.period"
            :step="1"
            controls-position="right"
            :min="4"
            :max="16"
            style="width:120px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="科目：" prop="subject">
          <el-input v-model="lessonForm.subject"></el-input>
        </el-form-item>
        <el-form-item label="性质：" prop="nature">
          <el-select v-model="lessonForm.nature" placeholder="请选择课程性质" style="width:100%">
            <el-option v-for="item in natures" :key="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学分：" prop="credit">
          <el-input-number
            v-model="lessonForm.credit"
            :precision="1"
            :step="0.5"
            controls-position="right"
            :min="0.0"
            :max="10.0"
            style="width:120px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="教师：" prop="teacher">
          <el-select v-model="lessonForm.teacher" placeholder="请选择教师" style="width:100%" filterable>
            <el-option
              v-for="item in teacherInfo"
              :key="item.label"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDrawer=false">取消</el-button>
          <el-button type="primary" @click="addLesson">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 修改课程弹出框 -->
    <el-drawer title="修改课程" :visible.sync="alterDrawer" direction="ltr" class="addDrawer">
      <el-form
        ref="alterFormRef"
        :rules="addFormRules"
        :model="lessonInfo"
        label-width="70px"
        size="medium"
        class="addLessonForm"
      >
        <el-form-item label="学年：" prop="year">
          <el-select v-model="lessonInfo.year" placeholder="请选择学年" style="width:100%">
            <el-option v-for="item in getYear" :key="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期：" prop="term">
          <el-radio-group v-model="lessonInfo.term">
            <el-radio :label="1">第一学期</el-radio>
            <el-radio :label="2">第二学期</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课时：" prop="period">
          <el-input-number
            v-model="lessonInfo.period"
            :step="1"
            controls-position="right"
            :min="4"
            :max="16"
            style="width:120px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="科目：" prop="subject">
          <el-input v-model="lessonInfo.subject"></el-input>
        </el-form-item>
        <el-form-item label="性质：" prop="nature">
          <el-select v-model="lessonInfo.nature" placeholder="请选择课程性质" style="width:100%">
            <el-option v-for="item in natures" :key="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学分：" prop="credit">
          <el-input-number
            v-model="lessonInfo.credit"
            :precision="1"
            :step="0.5"
            controls-position="right"
            :min="0.0"
            :max="10.0"
            style="width:120px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="教师：" prop="teacher">
          <el-select
            v-model="lessonInfo.teacher.username"
            placeholder="请选择教师"
            style="width:100%"
            filterable
            @focus="getTeacherId"
          >
            <el-option
              v-for="item in teacherInfo"
              :key="item.label"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="alterDrawer=false">取消</el-button>
          <el-button type="primary" @click="alterLesson">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 课程查询信息
      queryInfo: {
        year: '',
        term: null,
        subject: '',
        page: 1,
        size: 1
      },
      // 存储总数据条数
      total: 100,
      // 学期选项
      terms: [{ label: 1 }, { label: 2 }],
      // 提交表单
      lessonForm: {
        // 学年
        year: '',
        // 学期
        term: 1,
        // 课时
        period: 8,
        // 科目
        subject: '马克思原理',
        // 科目性质
        nature: '',
        // 学分
        credit: 1,
        // 教师
        teacher: ''
      },
      // 课程性质选项
      natures: [
        { label: '专业选修课' },
        { label: '专业必修课' },
        { label: '公共选修课' },
        { label: '公共必修课' }
      ],
      // 课程列表数据
      lessonData: [],
      // 控制添加课程的弹出框是否可见
      addDrawer: false,
      // 添加课程的表单验证规则
      addFormRules: {
        year: [{ required: true, message: '请选择学年', trigger: 'blur' }],
        term: [{ required: true, message: '请选择学期', trigger: 'blur' }],
        period: [{ required: true, message: '请选择课时', trigger: 'blur' }],
        subject: [{ required: true, message: '请输入课程', trigger: 'blur' }],
        nature: [
          { required: true, message: '请选择课程性质', trigger: 'blur' }
        ],
        credit: [{ required: true, message: '请选择学分', trigger: 'blur' }],
        teacher: [{ required: true, message: '请选择教师', trigger: 'blur' }]
      },
      // 保存教师信息
      teacherInfo: [],
      // 控制修改课程的弹出框是否可见
      alterDrawer: false,
      //  保存课程信息
      lessonInfo: {
        teacher: {
          username: '',
          _id: ''
        }
      }
    }
  },
  methods: {
    // 获取课程列表
    async getLessonList() {
      let res = await this.$http.get('lessons', { params: this.queryInfo })
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取课程列表失败')
      }
      // 获取成功
      this.lessonData = res.data.lessonData
      this.total = res.data.total * 10
    },
    // 当page变化时触发
    handlePageChange(newPage) {
      // 获取当前页数
      this.queryInfo.page = newPage
      // 刷新页面
      this.getLessonList()
    },
    // 展示添加课程抽屉
    showAddDrawer() {
      // 获取教师Id
      this.getTeacherId()
      // 打开抽屉
      this.addDrawer = true
    },
    // 获取教师Id
    async getTeacherId() {
      // 发送请求
      let res = await this.$http.get('users/teacherId')
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取教师信息失败')
      }
      // 获取成功
      this.teacherInfo = res.data
    },
    // 添加课程
    addLesson() {
      // 校验表单
      this.$refs.lessonFormRef.validate(async valid => {
        // 校验失败，直径返回
        if (!valid) return
        // 校验通过，发送请求
        let res = await this.$http.post('lessons', this.lessonForm)
        // 添加失败直接反回
        if (res.meta.status !== 201) {
          return this.$message.error('添加课程失败')
        }
        // 添加成功
        this.$message.success('添加课程成功')
        // 刷新课程列表
        this.getLessonList()
        // 关闭对话框
        this.addDrawer = false
      })
    },
    // 触发删除课程的确认框
    async isDeleteLesson(id) {
      let result = await this.$confirm(
        '此操作将永久删除该课程, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message.info('已取消删除')
      })

      if (result === 'confirm') {
        // 发起删除请求
        let res = await this.$http.delete('lessons', { params: { id } })
        // 删除失败
        if (res.meta.status !== 204) {
          return this.$message.error('删除失败')
        }
        // 删除成功
        this.$message.success('删除成功!')
        // 刷新列表
        this.getLessonList()
      }
    },
    // 获取课程信息
    async getLessonInfo(id) {
      // 发起请求
      let res = await this.$http.get('/lessons/info', { params: { id } })
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取课程信息失败')
      }
      // 获取成功
      this.lessonInfo = res.data
      // 打开修改对话抽屉
      this.alterDrawer = true
    },
    alterLesson() {
      this.$refs.alterFormRef.validate(async valid => {
        // 校验失败，直接返回
        if (!valid) return
        let teacher = this.lessonInfo.teacher
        // 判断是否更新teacher字段
        this.lessonInfo.teacher = teacher.username.includes('(')
          ? teacher._id
          : teacher.username

        // 发起更新请求
        let res = await this.$http.put('lessons', this.lessonInfo)
        // 更新失败，直接返回
        if (res.meta.status !== 201) {
          return this.$message.error('更新课程失败')
        }
        // 更新成功
        this.$message.success('更新课程成功')
        // 刷新列表
        this.getLessonList()
        // 关闭修改抽屉
        this.alterDrawer = false
      })
    }
  },
  computed: {
    getYear() {
      let years = []
      let current = new Date()
      let year = current.getFullYear() - 4

      for (let i = 0; i < 8; i++) {
        let obj = {}
        obj.label = [year + i, year + i + 1].join(' - ')
        years.push(obj)
      }
      return years
    }
  },
  created() {
    // 获取课程列表
    this.getLessonList()
  }
}
</script>

<style lang="less">
.lessonTable {
  margin: 40px 0 80px !important;
}
.addLessonForm .el-form-item__label {
  color: #99a9bf;
}
.addDrawer .el-drawer__body {
  padding: 0 20px;
}
</style>